import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/goods/UserVipGoodsDetail.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/order/OrderPageVip.dart';

import '../base/Constant.dart';

class UserUpdateListPage extends StatefulWidget {
  _UserUpdateListPageState createState() => _UserUpdateListPageState();
}

class _UserUpdateListPageState extends State<UserUpdateListPage> {
  List<GoodsListDataData> homeListData = new List();

  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  int currentShow = 0; //0 正常 1 网格
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadList();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: AppBar(
            title: Text(
              '升级店长',
              style: TextStyle(
                  color: black,
                  fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
            ),
            elevation: 0.5,
            backgroundColor: white,
            iconTheme: new IconThemeData(color: black_99),
            brightness: Brightness.light,
            actions: <Widget>[
              GestureDetector(
                  child: Container(
                    child: Text('礼包订单',
                        style: TextStyle(
                          color: mainColor,
                            fontSize: ScreenUtil.getInstance().setSp(32))),
                    color: white,
                    alignment: Alignment.center,
                    padding: EdgeInsets.all(10),
                  ),
                  onTap: () {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return new OrderVipPage();
                    }));
                  },
                  behavior: HitTestBehavior.opaque),
            ],
          ),
          resizeToAvoidBottomInset: false,
          body: new Column(
            children: <Widget>[
              Container(
                child: Image.asset(
                  "images/icon_privilege_top.png",
                  width: MediaQuery.of(context).size.width,
                  fit: BoxFit.fitWidth,
                ),
                padding: EdgeInsets.all(10),
              ),
              // Container(
              //   child: Image.asset(
              //     "images/icon_privilege_title.png",
              //   ),
              //   padding: EdgeInsets.all(10),
              // ),
              Container(
                child: Text('商城累计消费满365元',
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(25))),
                padding: EdgeInsets.all(3),
              ),
              Container(
                child: Text('或购买以下任意一件商品即可成为店长',
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(25))),
                padding: EdgeInsets.all(3),
              ),
              new Expanded(
                child: new EasyRefresh(
                  controller: _controller,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  enableControlFinishLoad: true,
                  enableControlFinishRefresh: true,
                  child: GridView.builder(
                    shrinkWrap: true,
                    padding: EdgeInsets.all(10),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        mainAxisSpacing: 10.0,
                        crossAxisSpacing: 10.0,
                        childAspectRatio: 0.6),
                    itemBuilder: (context, index) {
                      return _renderRow2(context, index);
                    },
                    itemCount: homeListData == null ? 0 : homeListData.length,
                  ),
                  onRefresh: () async {
                    page = 1;
                    loadList();
                  },
                  onLoad: () async {
                    page++;
                    loadList();
                  },
                ),
              ),
            ],
          )),
    );
  }

  loadList() async {
    FormData formData = new FormData.fromMap({
      "group_id": "2",
      "p": page,
      "per": 8,
    });
    Response<String> response = await HttpUtil()
        .post(Api.BaseUrl + "/index.php/wap/UserGoods/getList", data: formData);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity homeListEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          homeListData.clear();
          homeListData.addAll(homeListEntity.data.datas);
          _controller.finishRefresh();
        } else {
          homeListData.addAll(homeListEntity.data.datas);
          _controller.finishLoad();
        }
      });
    }
  }

  Widget _renderRow2(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: white,
        ),
        width: MediaQuery.of(context).size.width / 2,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            ClipRRect(
              child: homeListData[index].img == ""
                  ? Image.asset('images/app_icon.png',
                      width: (MediaQuery.of(context).size.width - 30) / 2,
                      fit: BoxFit.fill,
                      height: (MediaQuery.of(context).size.width - 30) / 2)
                  : CachedNetworkImage(
                      imageUrl: Api.ImgBaseUrl + homeListData[index].img,
                      width: (MediaQuery.of(context).size.width - 30) / 2,
                      fit: BoxFit.fill,
                      height: (MediaQuery.of(context).size.width - 30) / 2),
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Padding(
                padding: EdgeInsets.all(5),
                child: Text(
                  homeListData[index].goods_name,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(28),
                    color: black_99,
                  ),
                ),
              ),
            ),
            Padding(
                padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
                child: new Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "¥" + homeListData[index].price.toString(),
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(35),
                          color: black),
                    ),
                    Container(
                      width: 4,
                    ),
                    Text(
                      homeListData[index].old_price.toString(),
                      style: TextStyle(
                          decoration: TextDecoration.lineThrough,
                          fontSize: ScreenUtil.getInstance().setSp(26),
                          color: Colors.grey),
                    ),
                    // Padding(
                    //   padding: EdgeInsets.fromLTRB(0, 0, 5, 0),
                    //   child: Image.asset(
                    //     'images/icon_shop_car.png',
                    //     height: ScreenUtil.getInstance().setHeight(50),
                    //   ),
                    // )
                  ],
                )),
            Container(
              margin: EdgeInsets.all(5),
              width: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.all(5),
              decoration: BoxDecoration(
                  color: mainColor, borderRadius: BorderRadius.circular(5)),
              child: Text(
                "立即抢购",
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(26),
                    color: Colors.white),
              ),
            )
          ],
        ),
      ),
      onTap: () {
        if (APPLIC.userInfoMap['user_msg']['group_id'] == 2) {
          Fluttertoast.showToast(msg: "恭喜你已成为店长，继续加油哦！");
          return;
        }
        if (APPLIC.userInfoMap['user_msg']['group_id'] > 2) {
          Fluttertoast.showToast(msg: "你已高于店长，继续加油哦！");
          return;
        }
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return UserVipGoodsDetailPage(
            goods_id: homeListData[index].goods_id,
            img: homeListData[index].img,
          );
        }));
      },
    );
  }
}
